//
//  MainViewController.swift
//  TYBlog
//
//  Created by 杨远鹏 on 16/9/20.
//  Copyright © 2016年 TY. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {
    
    @objc private func clickComposedButton(){
        print("点我了")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
        
        setUpComposedButton()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        tabBar.bringSubviewToFront(composedButton)
    }

    lazy var composedButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backgroudImageName: "tabbar_compose_button")
}

extension MainViewController{
    
    private func setUpComposedButton(){
        let w = tabBar.bounds.width / CGFloat(childViewControllers.count) - 1
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        tabBar.addSubview(composedButton)
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    private func addChildViewControllers() {
        addChildViewController(HomeViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    /// 添加子控制器
    ///
    /// - parameter vc:        vc
    /// - parameter title:     标题
    /// - parameter imageName: 图片名
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "\(imageName)_selected")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orangeColor()], forState: UIControlState.Selected)
        let nc = UINavigationController(rootViewController: vc)
        addChildViewController(nc)
    }
}
